﻿using System.Text;

namespace HCommon
{
    public static class HttpHelper
    {
        /// <summary>
        /// 模拟Post请求
        /// </summary>
        /// <param name="url">请求Url</param>
        /// <param name="data">传递数据</param>
        /// <param name="header">请求头</param>
        /// <returns></returns>
        public static async Task<string> HttpPostAsync(string url, string data="", Dictionary<string, string>? header = null)
        {
            using var client = new HttpClient();
            if (header != null && header.Count > 0)
            {
                foreach (var key in header.Keys)
                {
                    client.DefaultRequestHeaders.Add(key, header[key]);
                }
            }
            var content = new StringContent(data, Encoding.UTF8, "application/json");
            var response = await client.PostAsync(url, content);
            return await response.Content.ReadAsStringAsync();
        }
        /// <summary>
        /// 模拟Get请求
        /// </summary>
        /// <param name="url">请求Url</param>
        /// <param name="header">请求头</param>
        /// <returns></returns>
        public static async Task<string> HttpGetAsync(string url, Dictionary<string, string>? header = null)
        {
            using var client = new HttpClient();
            if (header != null && header.Count > 0)
            {
                foreach (var key in header.Keys)
                {
                    client.DefaultRequestHeaders.Add(key, header[key]);
                }
            }
            var response = await client.GetAsync(url);
            return await response.Content.ReadAsStringAsync();
        }

        /// <summary>
        /// 模拟Put请求
        /// </summary>
        /// <param name="url">请求Url</param>
        /// <param name="data">传递数据</param>
        /// <param name="header">请求头</param>
        /// <returns></returns>
        public static async Task<string> HttpPutAsync(string url, string data = "", Dictionary<string, string>? header = null)
        {
            using var client = new HttpClient();
            if (header != null && header.Count > 0)
            {
                foreach (var key in header.Keys)
                {
                    client.DefaultRequestHeaders.Add(key, header[key]);
                }
            }
            var content = new StringContent(data, Encoding.UTF8, "application/json");
            var response = await client.PutAsync(url, content);
            return await response.Content.ReadAsStringAsync();
        }
    }
}